﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Web.Mvc;
using System.Web.Security;
using Sharp.Infrastructure;
using Sharp.Portal.Mvc.Models;

namespace Sharp.Portal.Mvc.Filter
{
    [DebuggerStepThrough]
    public class AuthorizeFilter : ActionFilterAttribute
    {
        //Action方法执行之前执行此方法       
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var allowAnonymous4Action =
                filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any();

            var allowAnonymous4Controller = filterContext.ActionDescriptor.ControllerDescriptor
                .GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any();
            if (allowAnonymous4Action || allowAnonymous4Controller)
            {
                return;
            }

            base.OnActionExecuting(filterContext);

            //foreach (var item in filterContext.ActionParameters)
            //{
            //    var model = item.Value as BaseViewModel;
            //    if (model != null)
            //    {
            //        model.OP = filterContext.HttpContext.User.Identity.Name;
            //    }
            //}

            var identity = filterContext.HttpContext.User.Identity;
            if (identity.IsAuthenticated)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var result = new
                    {
                        success = false,
                        errors = "请登录",
                        redirectToUrl = "/Account/Login"
                    };
                    filterContext.Result = new JsonResult
                    {
                        Data = result,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    if (!filterContext.HttpContext.Request.IsAuthenticated)
                    {
                        filterContext.HttpContext.Response.Redirect("/Account/Login");
                    }
                }

            }


        }
    }
}